<template>
	<div>
		<div class="header">



			<!-- title="智能供佛系统" -->

			<!-- left-arrow="true"
			left-text="返回" -->
			<van-nav-bar style="  background: linear-gradient(90deg, #41A9B7,#4fd4e2, #41A9B7);height: 5rem;line-height: 5rem; ">

				<span class="title" slot="title">存放确认</span>


				<span style="font-size: 1.5625rem ; color: white; font-weight: 500;" slot="right">

					<van-button type="primary" color="#348994" @click="back">&nbsp;返&nbsp;&nbsp;&nbsp;回&nbsp;</van-button>
				</span>



			</van-nav-bar>
			<!-- <van-nav-bar title="智能供佛系统" style=" background: url(./images/系统标题部分.png);height: 80px;line-height: 80px; background-size:1142px 80px;background-repeat:no-repeat;">
				<van-icon name="search" slot="right" />
			</van-nav-bar> -->
		</div>


		<!-- /////////////////////////////////////////////////////////// -->
		<div class="content" >



			<div style="width: 50%; height: 250px;  margin:1rem auto;  ">

				<div style=" line-height: 50px;	background: #348994; font-family: 楷体; font-size:2rem ;		border: #FFAE00 solid 2px; border-radius:10px;  width: 100%;  margin-left: auto; margin-right: auto; margin-top: 0px; margin-bottom: 50px;  text-align: left; font-size: 25px;font-weight: 550; color: #FFAE00;">

					<div style="margin-left: 10px; ">
						
						<span>龛位编号：{{ledList | ledName}}</span> <br>
						
						<span>逝者姓名：{{departedName}}</span><br>
						<span>逝者年龄：{{age}}</span><br>
						<span>安息时间：{{deathday}}</span><br>
						<span>圣&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名：{{baptismal_name}}</span><br>
						<span>家属姓名：{{userName}}</span><br>
						<span>家属手机：{{phoneNumber}}</span><br>
						
						<span>追思寄语：{{qifutext}}</span><br>
						<span>存放时长：{{priceTitle}}</span><br>
						<span>金&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;额：{{total_fee}}元</span><br>


					</div>

				</div>

				<div style="margin-top: -2rem ;">
					<div style="font-size: 1.25rem;color: #226254; font-weight: bold; font-family: 楷体;">
						选择支付方式
					</div>
					<!-- 微信支付 -->
					<van-image @click="wxPay" width="13rem" height="11rem" src="./images/wxpay.png" />

					<!-- 现场支付 -->
					<van-image @click="adminPay" style="margin-left: 12rem ;" width="13rem" height="11rem" src="./images/cashpay.png" />

				</div>












				<!--<van-button color="#EEA313" size="large" style="margin-top: 20px;" @click="login">登入</van-button> -->




				<!-- 键盘 -->

				<!-- style="width: 50%; height: 40%; margin-left: 25%;" 键盘样式-->
				<van-number-keyboard style="width: 50%; height: 35%; margin-left: 25%;" :show="keybord" theme="custom" extra-key="."
				 close-button-text="完成" @blur="keybord = false" @input="onInput" @delete="onDelete" />

				<!-- ///////////////////////////////////////////////////////////////弹出框微信扫码支付-->

				<van-dialog v-model="dialogShow" title="微信支付" @cancel="beforeClose()" :show-cancel-button="true" :showConfirmButton="false"
				 style="width: 37.5rem;">
					<div v-if="isPay">
						<div style="margin-top: 50px;">
						</div>
						<van-image src="./images/paySuccess.jpg" width="18.75rem" height="18.75rem" />
						<div style="font-size: 2.8125rem; font-weight:600; color: #42AF35; margin-bottom: 3.125rem;">
							支付成功
						</div>
					</div>
					<div v-else>
						<van-image :src="QRCode" width="25rem" height="25rem" />
						<div>
							<van-image src="./images/wxpay2.jpg" width="18.75rem" height="3.75rem" />
						</div>
					</div>
				</van-dialog>


				<!-- /////////管理员刷卡弹出层/////////////////////////////////////////////////////////////////////////// -->
				<van-dialog v-model="dialogShowAdmin" title="管理员支付" @cancel="beforeClose()" :show-cancel-button="true"
				 :showConfirmButton="false" style="width: 37.5rem;">

					<!-- <div v-if="isPay">
						<div style="margin-top: 50px;">
				
						</div>
				
						<img src="./images/paySuccess.jpg" width="300" height="300">
						<div style="font-size: 45px; font-weight:600; color: #42AF35; margin-bottom: 50px;">
							支付成功
						</div>
					</div> -->

					<div>
						<div style="margin: 1rem auto; ">
							<!-- <span style="font-size: 1.25rem;">请在10秒内完成操作</span> -->
						</div>

						<!-- xjpaytishiyu -->
						<van-image src="./images/cashcard.png" width="18.75rem" height="18.75rem" style="margin-bottom: 1rem;" />

						<div>
							<van-image src="./images/xjpaytishiyu.png" width="18.75rem" height="3.75rem" />
						</div>

					</div>
				</van-dialog>



				<!-- 
				
			供佛账号： 输入
			
			 
			
			
			
			
			
			选择时长：一周，一天
			
			
			
			确认信息  价格，账号，数量
			
			
			
			选择支付方式 -->




			</div>



		</div>
		<!-- /////////////////////////////////////////////////////////// -->


	</div>

</template>

<script>
	export default {


		data() {
			return {
				cprice:{},
				led_price:{},
				deathdayObj:{},
				priceTitle:'',
				total_fee: 0,
				ledList: [],
				day: 0,
				orderInfor: {}, //订单信息
				keybord: false,
				phoneNumber: '13929597898',
				qifutext: '',
				supplytime:null,
				userName: '',
				departedName:'',
				baptismal_name:'',
				age:'',
				deathday: '',
				mes: '',
				dialogVisible: false,
				dialogShow: false,
				dialogShowAdmin: false,
				isPay: false,
				QRCode: null,
				intervalId: 0, //查询订单定时器
				errormessage: '',
				cancelCard: false

			}
		},
		methods: {



			checkPhoneNumber() {
				if (!(/^1[3456789]\d{9}$/.test(this.phoneNumber))) {
					this.errormessage = "格式不正确，请输入正确的手机号码！";
					return false;
				} else {
					this.errormessage = "";
					return true;
				}
			},
			
			back() {
				
				this.$router.push({
						path: '/GongfoStep0_2',
						query: {
							total_fee: this.total_fee,
							ledList: this.ledList,
							//day: this.day,
							//priceTitle: this.cprice.title,
							userName: this.userName,
							phoneNumber: this.phoneNumber,
							qifutext: this.qifutext,
							departedName: this.departedName,
							baptismal_name: this.baptismal_name, //圣名
							age: this.age,
							//deathday: tempDate,
							deathdayObj:this.deathdayObj,
							cprice:this.cprice,
							led_price:this.led_price,
							backShow:1
						}
					});	
			
			},

			isInput() {
				this.keybord = true;
				this.errormessage = '';

			},
			onInput(value) {
				this.phoneNumber += value;
			},
			onDelete() {
				this.phoneNumber = this.phoneNumber.substring(0, this.phoneNumber.length - 1);
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
					.then(_ => {
						done();
					})
					.catch(_ => {});
			},
			////////////////////////////////////////////////////////////////////////////////////////////////////
			beforeClose() {

				// let evtObj = document.createEvent('UIEvents'); 
				// evtObj.initUIEvent( "keydown", true, true, window, 1 );
				// delete evtObj.keyCode;
				// Object.defineProperty(evtObj,"keyCode",{value:13});


				this.cancelCard = true;



				clearInterval(this.intervalId);


				this.$toast.fail({
					message: '已取消支付'
				});
				console.log("支付取消了.............................")
			},
			/* 吊起微信扫码支付 */
			wxPay() {
				
				if(this.$store.getters.getTempleData.online_payment_off==1){
					this.$toast.fail("暂未开放微信支付");
					return;
				}
				
				
				if (!this.checkPhoneNumber()) {
					return;
				}

				//生成唯一订单号 //可用于查询微信订单状态
				let out_trade_no = '';
				for (var i = 0; i < 4; i++) //4位随机数，用以加在时间戳后面。
				{
					out_trade_no += Math.floor(Math.random() * 10);
				}
				out_trade_no = new Date().getTime() + out_trade_no; //时间戳，用来生成订单号。




				//parseInt(7.000001,10)这个也可以
				console.log("total_fee====================>>", Math.floor((this.total_fee * 100)));

				this.axios.get('https://xf.mianmianshi.com/wxPay/getQRCode', {
						responseType: 'arraybuffer',
						params: {
							out_trade_no: out_trade_no,
							total_fee: Math.floor((this.total_fee * 100)),
							body: this.$store.getters.getWeixinMes.name,
							product_id: "1", //led类型
							//微信支付基本参数
							appid: this.$store.getters.getWeixinMes.appid,
							mch_id: this.$store.getters.getWeixinMes.mch_id,
							key: this.$store.getters.getWeixinMes.key
						}

					})
					.then((res) => {
						/* 处理图片 */
						this.QRCode = 'data:image/png;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(
							byte), ''));
						this.dialogShow = true;


						//开始查询订单，判断用户支付状态
						this.intervalId = setInterval(() => {
							console.log("查询订单状态。。。。。。。。。。。。。。。。。。")
							if (this.isPay) {
								clearInterval(this.intervalId); //关闭定时器
							} else {
								this.isPaid(out_trade_no);
							}
						}, 1000);
						//


					})
					.catch(function(error) {
						console.log(error);
					});

			},

			isPaid(out_trade_no) {
				/* 查询订单是否支付成功 */
				this.axios.post('https://xf.mianmianshi.com/wxPay/findOrder', {
						appid: this.$store.getters.getWeixinMes.appid,
						mch_id: this.$store.getters.getWeixinMes.mch_id,
						key: this.$store.getters.getWeixinMes.key,
						out_trade_no: out_trade_no
					})
					.then((res) => {
						console.log("payRes============================================", res)
						if (res.data.trade_state == "SUCCESS") { //支付成功 1添加订单，2获取用户信息，准备跳转用户中心
							this.isPay = true;


							//1添加订单
							this.addOrder(out_trade_no);

							//查询用户信息 ，添加到store
							/* 	this.axios.post('https://mianmianshi.com/cms/temple/client/findUser', {
										where: {
											phone_number: this.phoneNumber
										}

									})
									.then((res) => {
										if (res.data.id) {
											this.$store.commit("setUser", res.data);
										}

										const toast = this.$toast.loading({
											duration: 0, // 持续展示 toast
											forbidClick: true, // 禁用背景点击
											loadingType: 'spinner',
											message: '支付成功即将前往个人中心，倒计时 3 秒'
										});

										let second = 3;
										const timer = setInterval(() => {
											second--;
											if (second) {
												toast.message = `支付成功即将前往个人中心，倒计时 ${second} 秒`;
											} else {
												clearInterval(timer);
												this.$toast.clear();
												this.$router.push("consumer");
											}
										}, 1000);

									})
									.catch(function(error) {
										console.log(error);
									}); */
							/////////////////////////////////
						}

					})
					.catch(function(error) {
						console.log(error);
					});
			},

			listenForCard() {

				this.cancelCard = false;
				let _this = this;
				let keyNumber = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
				let event_card_no = '';
				/* 监听键盘事件-读卡 */
				function fn(e) {
					//event_card_no='';

					for (let i = 0; i < 10; i++) {
						if (e.keyCode == keyNumber[i]) {
							event_card_no += i;
							break;
						} else if (e.keyCode == 13) {
							console.log(event_card_no);
							//event_card_no='';	
							document.removeEventListener("keydown", fn);
							console.log("移除了该事件");
							_this.doAdminPay(event_card_no);
							break;
						}


					}
				}

				document.addEventListener("keydown", fn);

				/* 查看是否需要关闭监听事件 */
				let cardInterval = setInterval(() => {
					console.log(this.cancelCard);
					if (this.cancelCard) {
						document.removeEventListener("keydown", fn);
						clearInterval(cardInterval);
					}
				}, 500)






			},

			async doAdminPay(card_no) {
				//读到了卡数据，进行处理
				///////////////////////////////////////////////////////////////////////
				await this.axios.post('https://mianmianshi.com/cms/temple/client/findUser', {
						'where': {
							card_no: card_no,
							tid: this.$store.getters.getTid
						}
					})
					.then((res) => {
						//判断是不是该寺庙管理员
						if (res.data.identity == "ADMIN") {

							//1添加订单 //管理员支付时，微信订单号统一为0
							this.addOrder(0);



						} else { //其他卡号

							this.$toast.fail("非管理员-没有权限进行操作！");
							this.dialogShowAdmin = false;
						}


					})
					.catch(function(error) {
						console.log(error);
					});

				///////////////////////////////////////////////////////////////////////
			},

			/* 管理员支付*/
			adminPay(card_no) {

				//alert(this.phoneNumber)

				if (!this.checkPhoneNumber()) {
					return;
				}
				this.dialogShowAdmin = true;
				//1吊起刷卡程序
				this.listenForCard();









				/* 	this.axios.post('http://localhost:8088/readCard')
						.then((res) => {
							console.log(res);
							if (res.data == "timeout") { //超时
								this.$toast.fail("刷卡超时！");
								this.dialogShowAdmin = false;


							} else {}
						})
						.catch(function(error) {
							console.log(error);
						}); */

				//2验证管理员是否已收款
			},
			/* 支付成功时，添加订单 */
			async addOrder(out_trade_no) {


				await this.axios.post('https://mianmianshi.com/cms/temple/client/addOrder', {
						ledList: this.ledList,
						user: {
							tid: this.$store.getters.getTid,
							user_name: this.userName,
							phone_number: this.phoneNumber,
							identity: "CONSUMER" //用户身份，这里是普通用户
						},
						order: {
							tid: this.$store.getters.getTid,
							state: 1, // state 1已付款		 3已完成 （订单表）
							keeptime: this.day * 24 * 60 * 60 * 1000,
							supplytime: this.dokeeptime(this.day), //为了兼容后台页面数据展示，本来是没必要的 2019年12月9日，添加
							telephone: this.phoneNumber, //为了兼容后台页面数据展示，本来是没必要的
							uname: this.userName, //为了兼容后台页面数据展示，本来是没必要的，现在他是订单的属性，不一定是username
							create_time: new Date().getTime(),
							starttime: new Date().getTime(),
							endtime: new Date().getTime() + this.day * 24 * 60 * 60 * 1000,
							type: 5, //付款类型，当前为访客机
							price: this.total_fee, //订单价格
							ledmes: JSON.stringify(this.ledList),
							qifutext: this.qifutext,
							user_id: 0, //初始未知，后端处理赋值
							out_trade_no: out_trade_no,
							departed:this.departedName,

							baptismal_name:this.baptismal_name,
							age:this.age,
							deathday_str:this.deathday //deathday:this.deathday
							
							

						}

					})
					.then((res) => {

						if (res.data) {

							///////////////////////////////////////////////////////////////////////
							//查询用户信息(购买人) ，添加到store
							this.axios.post('https://mianmianshi.com/cms/temple/client/findUser', {
									where: {
										phone_number: this.phoneNumber,
										tid: this.$store.getters.getTid
									}

								})
								.then((res) => {
									if (res.data.id) {
										this.$store.commit("setUser", res.data);
									}

									const toast = this.$toast.loading({
										duration: 0, // 持续展示 toast
										forbidClick: true, // 禁用背景点击
										loadingType: 'spinner',
										message: '支付成功即将前往个人中心，倒计时 3 秒'
									});

									let second = 3;
									const timer = setInterval(() => {
										second--;
										if (second) {
											toast.message = `支付成功即将前往个人中心，倒计时 ${second} 秒`;
										} else {
											clearInterval(timer);
											this.$toast.clear();
											this.$router.push("consumer");
										}
									}, 1000);

								})
								.catch(function(error) {
									console.log(error);
								});
							//////////////////////////////////////////////////////////////////////

						}

					})
					.catch(function(error) {
						console.log(error);
					});
			},
			dokeeptime(day) {

				let m = day / 30;
				let y = day / 365;

				if (m > 1 && m < 12) {
					return m + "个月";
				} else if (y >= 1) {
					return y + "年";
				} else {
					return day + "天";
				}


			}


		},

		created() {
			this.total_fee = this.$route.query.total_fee;
			this.ledList = this.$route.query.ledList;
			this.day = this.$route.query.day;
			this.phoneNumber = this.$route.query.phoneNumber;
			this.userName = this.$route.query.userName;
			this.qifutext = this.$route.query.qifutext;
			this.departedName=this.$route.query.departed;
			this.priceTitle=this.$route.query.priceTitle;
			this.baptismal_name=this.$route.query.baptismal_name;
			this.age=this.$route.query.age;
			this.deathday=this.$route.query.deathday;
			this.deathdayObj=this.$route.query.deathdayObj;
			this.cprice=this.$route.query.cprice;
			this.led_price=this.$route.query.led_price;
			
			
			
		
			
			

		},
		mounted() {





		},
		filters: {
			
			dateFilter(time) {
				
			/* 	if (time == "" || date == null) {
					return "";
				} */
				
				let date =new Date(time);
				
				console.log(date);
				
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				
				console.log("wwwwwwwwwwwww ",year + "年" + month + "月" + day + "日");
				return year + "年" + month + "月" + day + "日";
			},
			
			ledName(value) {

				let str = "";
				for (let i = 0; i < value.length; i++) {

					if (i == value.length - 1) {

						str = str + value[i].code;

					} else {
						str = str + value[i].code + ","

					}
				}

				if (str.length > 20) {
					str = str.substring(0, 20) + "....";
				}


				return str;
			}
		}

	}
</script>

<style>

</style>
